package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Date;

//自定义元数据对象处理器
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpSession httpSession;

    //MetaObject:表示的就是你要填充的对象
    //插入操作，自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        metaObject.setValue("createTime", new Date());
        metaObject.setValue("updateTime", new Date());

        Employee currentEmployee = EmployeeHolder.get();

        //从session中取出当前登录的用户currentEmployee
        //Employee currentEmployee = (Employee) httpSession.getAttribute("SESSION_EMPLOYEE");

        if (currentEmployee != null) {
            metaObject.setValue("createUser", currentEmployee.getId());
            metaObject.setValue("updateUser", currentEmployee.getId());
        }

        User user = UserHolder.get();
        if(user != null){
            metaObject.setValue("createUser",user.getId());
            metaObject.setValue("updateUser",user.getId());
        }
    }

    //更新操作，自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime", new Date());

        //使用ThreadLocal+拦截器
        Employee currentEmployee = EmployeeHolder.get();

        //从session中取出当前登录的用户currentEmployee   不用这种方法
        //Employee currentEmployee = (Employee) httpSession.getAttribute("SESSION_EMPLOYEE");

        if (currentEmployee != null) {
            metaObject.setValue("updateUser", currentEmployee.getId());
        }

        User user = UserHolder.get();
        if(user != null){
            metaObject.setValue("updateUser",user.getId());
        }
    }
}